﻿using System;
using System.Collections.Generic;
using System.IO;

namespace WS.EKA.Utilities.Helpers
{
    public class PictureConverter
    {
        private static Dictionary<string, string> Pictures { get; set; }
        private static object obj = new object();
        public static string GetBase64String(string ImagePath)
        {
            if (Pictures == null) Pictures = new Dictionary<string, string>();
            string picString = string.Empty;
            Pictures.TryGetValue(ImagePath, out picString);
            if (string.IsNullOrEmpty(picString))
            {
                picString = AddPictureToDictionary(ImagePath);
            }
            return picString;
        }

        private static string AddPictureToDictionary(string ImagePath)
        {
            lock (obj)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + ImagePath;
                byte[] imageBytes = null;
                using (var fileStream = new FileStream(path, FileMode.Open))
                {
                    imageBytes = new byte[fileStream.Length];
                    fileStream.Read(imageBytes, 0, (int)fileStream.Length);
                }
                string pic = "data:image/jpeg;base64," + Convert.ToBase64String(imageBytes);
                Pictures.Add(ImagePath, pic);
                return pic;
            }
        }
    }
}
